package com.evan.review.architecture.mvp;

import android.app.AlertDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.evan.review.R;
import com.evan.review.architecture.mvp.contract.UserContract;
import com.evan.review.architecture.mvp.model.User;
import com.evan.review.architecture.mvp.presenter.UserPresenter;
import com.evan.review.architecture.mvp.view.adapter.UserAdapter;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;
import java.util.List;

/**
 * MVP架构示例Activity
 * 实现UserContract.View接口，负责UI展示
 */
public class MVPExampleActivity extends AppCompatActivity implements UserContract.View {

    private UserContract.Presenter presenter;
    private UserAdapter adapter;
    private RecyclerView rvUsers;
    private ProgressBar progressBar;
    private TextView tvEmptyView;
    private EditText etSearch;
    private Button btnSearch;
    private Button btnAllUsers;
    private Button btnActiveUsers;
    private FloatingActionButton fabAddUser;

    // 用于在主线程更新UI
    private final Handler mainHandler = new Handler(Looper.getMainLooper());

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mvp_example);

        // 初始化Presenter
        presenter = new UserPresenter();
        presenter.attachView(this);

        // 初始化视图
        initViews();

        // 设置点击事件
        setupClickListeners();

        // 加载用户数据
        presenter.loadUsers();
    }

    private void initViews() {
        rvUsers = findViewById(R.id.rv_users);
        progressBar = findViewById(R.id.progress_bar);
        tvEmptyView = findViewById(R.id.tv_empty_view);
        etSearch = findViewById(R.id.et_search);
        btnSearch = findViewById(R.id.btn_search);
        btnAllUsers = findViewById(R.id.btn_all_users);
        btnActiveUsers = findViewById(R.id.btn_active_users);
        fabAddUser = findViewById(R.id.fab_add_user);

        // 设置RecyclerView
        rvUsers.setLayoutManager(new LinearLayoutManager(this));
        adapter = new UserAdapter(this, new ArrayList<>(), new UserAdapter.UserClickListener() {
            @Override
            public void onUserClick(User user) {
                presenter.getUserDetails(user.getId());
            }

            @Override
            public void onUserEditClick(User user) {
                presenter.startEditUser(user.getId());
            }

            @Override
            public void onUserDeleteClick(User user) {
                showDeleteConfirmationDialog(user);
            }

            @Override
            public void onUserToggleStatusClick(User user) {
                presenter.toggleUserActiveStatus(user.getId());
            }
        });
        rvUsers.setAdapter(adapter);
    }

    private void setupClickListeners() {
        // 搜索按钮点击事件
        btnSearch.setOnClickListener(v -> {
            String query = etSearch.getText().toString().trim();
            presenter.searchUsers(query);
        });

        // 搜索文本变化监听
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().isEmpty()) {
                    presenter.loadUsers();
                }
            }
        });

        // 所有用户按钮点击事件
        btnAllUsers.setOnClickListener(v -> presenter.loadUsers());

        // 活跃用户按钮点击事件
        btnActiveUsers.setOnClickListener(v -> presenter.loadActiveUsers());

        // 添加用户按钮点击事件
        fabAddUser.setOnClickListener(v -> presenter.startAddUser());
    }

    private void showDeleteConfirmationDialog(User user) {
        new AlertDialog.Builder(this)
                .setTitle("删除用户")
                .setMessage("确定要删除用户 " + user.getName() + " 吗？")
                .setPositiveButton("删除", (dialog, which) -> {
                    presenter.deleteUser(user.getId());
                })
                .setNegativeButton("取消", null)
                .show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 解除View绑定，防止内存泄漏
        presenter.detachView();
    }

    // UserContract.View接口实现

    @Override
    public void showUsers(List<User> users) {
        mainHandler.post(() -> adapter.updateData(users));
    }

    @Override
    public void showUserDetails(User user) {
        mainHandler.post(() -> {
            // 显示用户详情对话框
            new AlertDialog.Builder(this)
                    .setTitle("用户详情")
                    .setMessage(getUserDetailsMessage(user))
                    .setPositiveButton("关闭", null)
                    .show();
        });
    }

    private String getUserDetailsMessage(User user) {
        return "ID: " + user.getId() + "\n" +
                "姓名: " + user.getName() + "\n" +
                "邮箱: " + user.getEmail() + "\n" +
                "电话: " + user.getPhone() + "\n" +
                "年龄: " + user.getAge() + "\n" +
                "状态: " + (user.isActive() ? "活跃" : "禁用");
    }

    @Override
    public void showLoading() {
        mainHandler.post(() -> progressBar.setVisibility(View.VISIBLE));
    }

    @Override
    public void hideLoading() {
        mainHandler.post(() -> progressBar.setVisibility(View.GONE));
    }

    @Override
    public void showError(String message) {
        mainHandler.post(() -> Toast.makeText(this, message, Toast.LENGTH_SHORT).show());
    }

    @Override
    public void showSuccess(String message) {
        mainHandler.post(() -> Toast.makeText(this, message, Toast.LENGTH_SHORT).show());
    }

    @Override
    public void showEmptyView() {
        mainHandler.post(() -> {
            rvUsers.setVisibility(View.GONE);
            tvEmptyView.setVisibility(View.VISIBLE);
        });
    }

    @Override
    public void hideEmptyView() {
        mainHandler.post(() -> {
            rvUsers.setVisibility(View.VISIBLE);
            tvEmptyView.setVisibility(View.GONE);
        });
    }

    @Override
    public void navigateToAddUser() {
        // 在实际应用中，这里应该跳转到添加用户的Activity
        // 为了简化示例，这里使用对话框
        showAddEditUserDialog(null);
    }

    @Override
    public void navigateToEditUser(User user) {
        // 在实际应用中，这里应该跳转到编辑用户的Activity
        // 为了简化示例，这里使用对话框
        showAddEditUserDialog(user);
    }

    private void showAddEditUserDialog(User user) {
        // 创建一个简单的表单对话框
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_add_edit_user, null);

        EditText etName = dialogView.findViewById(R.id.et_user_name);
        EditText etEmail = dialogView.findViewById(R.id.et_user_email);
        EditText etPhone = dialogView.findViewById(R.id.et_user_phone);
        EditText etAge = dialogView.findViewById(R.id.et_user_age);

        // 如果是编辑模式，填充现有数据
        if (user != null) {
            etName.setText(user.getName());
            etEmail.setText(user.getEmail());
            etPhone.setText(user.getPhone());
            etAge.setText(String.valueOf(user.getAge()));
        }

        String title = user == null ? "添加用户" : "编辑用户";

        new AlertDialog.Builder(this)
                .setTitle(title)
                .setView(dialogView)
                .setPositiveButton("保存", (dialog, which) -> {
                    // 获取输入的数据
                    String name = etName.getText().toString().trim();
                    String email = etEmail.getText().toString().trim();
                    String phone = etPhone.getText().toString().trim();
                    String ageStr = etAge.getText().toString().trim();

                    // 简单验证
                    if (name.isEmpty() || email.isEmpty() || phone.isEmpty() || ageStr.isEmpty()) {
                        showError("所有字段都必须填写");
                        return;
                    }

                    int age;
                    try {
                        age = Integer.parseInt(ageStr);
                    } catch (NumberFormatException e) {
                        showError("年龄必须是数字");
                        return;
                    }

                    // 创建或更新用户
                    if (user == null) {
                        // 添加新用户
                        User newUser = new User();
                        newUser.setName(name);
                        newUser.setEmail(email);
                        newUser.setPhone(phone);
                        newUser.setAge(age);
                        newUser.setActive(true);
                        newUser.setAvatar("https://randomuser.me/api/portraits/men/1.jpg"); // 默认头像

                        presenter.addUser(newUser);
                    } else {
                        // 更新现有用户
                        user.setName(name);
                        user.setEmail(email);
                        user.setPhone(phone);
                        user.setAge(age);

                        presenter.updateUser(user);
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }
} 